/**
 * TmCustomFactoryAction.java
 * Created at 2017-3-1
 * Created by zhangzhiqiang002
 * Copyright (C) 2017 BROADTEXT SOFTWARE, All rights reserved.
 */
package com.broadtext.rms.basic.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.broadtext.common.bean.EntityPageBean;
import com.broadtext.common.exp.DaoException;
import com.broadtext.common.exp.ServiceException;
import com.broadtext.common.utils.RmsUtil;
import com.broadtext.rms.basic.model.TmCustomFactory;
import com.broadtext.rms.basic.model.TrPackCustomFactory;
import com.broadtext.rms.basic.service.ITmCustomFactoryService;
import com.broadtext.rms.basic.service.ITmCustomService;
import com.broadtext.rms.system.service.ISysUserService;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;

/**
 * <p>ClassName: TmCustomFactoryAction</p>
 * <p>Description: 客户厂区控制层</p>
 * <p>Author: zhangzhiqiang002</p>
 * <p>Date: 2017-3-1</p>
 */
@Controller
@RequestMapping("/main/factory")
public class TmCustomFactoryAction {
    /**o
     * 注入service
     */
    @Autowired
    @Qualifier("tmCustomFactoryService")
    private ITmCustomFactoryService tmCustomFactoryService;
    
    @Autowired
    @Qualifier("tmCustomService")
    private ITmCustomService tmCustomService;
    
    /**
     * 用户Service
     */
    @Autowired
    @Qualifier("sysUserService")
    private ISysUserService sysUserService;
    
    /**
     * <p>
     * Description: 列表查询
     * </p>
     * 
     * @param request 请求对象
     * @param response 返回对象
     */
    @RequestMapping(value = "/getCustomFactories.mvc")
    @ResponseBody
    public void getCustomFactories(HttpServletRequest request, HttpServletResponse response) {
        try {
            PageBounds pageBounds;
            pageBounds = new PageBounds();
            Map<String, Object> map;
            String aoData;
            aoData = request.getParameter("aoData");
            JSONArray array;
            array = JSON.parseArray(aoData);
            map = new HashMap<String, Object>();
            if (array != null) {
                Iterator<Object> it;
                it = array.iterator();
                while (it.hasNext()) {
                    JSONObject obj;
                    obj = (JSONObject) it.next();
                    if (obj.get("value") != null && !"".equals(obj.get("value") + "")) {
                        map.put(obj.get("name") + "", obj.get("value"));
                    }
                }
            }
            //判断登录账户类型，如果为客户账户则过滤数据，客户类型只看本级和本下级
            Map<String, Object> checkMap;
            List<String> list;
            try {
                checkMap = this.sysUserService.checkUserClass(request.getSession().getAttribute("sys.user").toString());
                if(null != checkMap && "true".equals(checkMap.get("flag").toString())){
                    //该用户是客户账号
                    map.put("cusId", checkMap.get("cusId"));
                    //查询当前登录用户所有下属子节点pk_id
                    list = this.tmCustomService.getChildCusIdArray(checkMap.get("cusId")+"");
                    map.put("ids", list);
                }
            } catch (DaoException e1) {
                e1.printStackTrace();
            }
            pageBounds.setLimit(Integer.parseInt(map.get("iDisplayLength").toString()));
            pageBounds.setPage(Integer.parseInt(map.get("iDisplayStart").toString()) / pageBounds.getLimit() + 1);
            EntityPageBean<TmCustomFactory> pageBean = this.tmCustomFactoryService.findEntityPageByQuery(map, pageBounds);
            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("recordsTotal", pageBean.getiTotalRecords());
            dataMap.put("recordsFiltered", pageBean.getiTotalRecords());
            dataMap.put("aaData", pageBean.getResults());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = null;
            try {
                out = response.getWriter();
                out.write(JSON.toJSONString(dataMap));
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        } catch (ServiceException e) {
            e.printStackTrace();
        }

    }
    
    /**
     * 
     * <p>Description: 新增或更新厂区</p>
     * @param factory 厂区对象
     * @param request 请求对象
     * @param response 返回对象
     */
    @RequestMapping(value = "/saveOrUpdateCustomFactory.mvc")
    @ResponseBody
    public void saveOrUpdateCustomFactory(TmCustomFactory factory,HttpServletRequest request, HttpServletResponse response) throws DaoException {
        String loginName;
        loginName = String.valueOf(request.getSession().getAttribute("sys.userName"));
        if (!"".equals(factory.getPkId())) {
            //编辑
            this.tmCustomFactoryService.updateCustomFactory(factory, loginName);
        } else {
            //新增
            this.tmCustomFactoryService.insertCustomFactory(factory, loginName);
        }
    }
    
    /**
     * 
     * <p>Description: 查询厂区</p>
     * @param id 厂区主键id
     * @param request 请求对象
     * @param response 返回对象
     */
    @RequestMapping(value = "/initCustomFactoryEdit.mvc")
    @ResponseBody
    public void getCustomFactoryById(String id,HttpServletRequest request, HttpServletResponse response) throws ServiceException {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            map.put("factory", this.tmCustomFactoryService.getCustomFactoryById(id));
        } catch (DaoException e) {
            e.printStackTrace();
        }
        //判断登录账户类型，如果为客户账户则过滤数据，客户类型只看本级和本下级
        Map<String, Object> checkMap;
        String parentId = "";
        try {
            checkMap = this.sysUserService.checkUserClass(request.getSession().getAttribute("sys.user").toString());
            if(null != checkMap && "true".equals(checkMap.get("flag").toString())){
                parentId = checkMap.get("cusId")+"";
            }
        } catch (DaoException e1) {
            e1.printStackTrace();
        }
        map.put("cusDict", this.tmCustomService.getParentCusOption(parentId, null));
        RmsUtil.writeJsonStr(response, JSON.toJSONString(map));
    }
    
    /**
     * 
     * <p>Description: 查询厂区详情</p>
     * @param id 厂区主键id
     * @param request 请求对象
     * @param response 返回对象
     */
    @RequestMapping(value = "/getCustomFactoryDetail.mvc")
    @ResponseBody
    public void getCustomFactoryDetail(String id,HttpServletRequest request, HttpServletResponse response) throws DaoException {
        Map<String, Object> map = new HashMap<String, Object>();
        map = this.tmCustomFactoryService.getCustomFactoryDetail(id);
        RmsUtil.writeJsonStr(response, JSON.toJSONString(map));
    }
    
    /**
     * 
     * <p>Description: 初始化电池关联绑定页面</p>
     * @param id 厂区主键id
     * @param request 请求对象
     * @param response 返回对象
     */
    @RequestMapping(value = "/initBatteryCorrelation.mvc")
    @ResponseBody
    public void initBatteryCorrelation(String id,HttpServletRequest request, HttpServletResponse response) throws DaoException {
        Map<String, Object> map = new HashMap<String, Object>();
        map = this.tmCustomFactoryService.initBatteryCorrelation(id);
        RmsUtil.writeJsonStr(response, JSON.toJSONString(map));
    }
    
    /**
     * 
     * <p>Description: 电池关联绑定</p>
     * @param tmPackCustomFactory 电池于客户厂区关联对象
     * @param request 请求对象
     * @param response 返回对象
     */
    @RequestMapping(value = "/saveBatteryCorrelation.mvc")
    @ResponseBody
    public void saveBatteryCorrelation(TrPackCustomFactory tmPackCustomFactory,HttpServletRequest request, HttpServletResponse response) throws DaoException {
        String loginUser;
        loginUser = String.valueOf(request.getSession().getAttribute("sys.userName"));
        this.tmCustomFactoryService.saveBatteryCorrelation(tmPackCustomFactory, loginUser);
    }
    
    /**
     * <p> Description: 删除  </p>
     * @param request 请求
     * @param pkId id
     * @param response 返回对象
     * @throws DaoException 异常
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping(value = "/delete.mvc")
    @ResponseBody
    public void delete(HttpServletRequest request, String pkId, HttpServletResponse response) throws DaoException {
        String[] idArray;
        idArray = pkId.split(",");
        String updateUser;
        updateUser = String.valueOf(request.getSession().getAttribute("sys.userName"));
        String flag;
        flag = this.tmCustomFactoryService.delete(idArray, updateUser);
        Map dataMap;
        dataMap = new HashMap();
        dataMap.put("msg", flag);
        RmsUtil.writeJsonStr(response, JSON.toJSONString(dataMap));
    }

}
